package com.lenovo.smarttraffic.ui.activity.stage3;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.WeatherBean;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

public class ForecastActivity extends BaseActivity {

    private TextView mTvTitle;

    private ImageView mIvStateImage;

    private RecyclerView mRvInfo;

    private LineChart mLcTable;

    private RecyclerView mRvIndex;

    private Handler handler = new Handler();

    @Override
    protected int getLayout() {
        return R.layout.activity_forecast;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolBar(this, "天气预报");

        mTvTitle = findViewById(R.id.tv_title);
        mIvStateImage = findViewById(R.id.iv_state_image);

        mRvInfo = findViewById(R.id.rv_info);
        mLcTable = findViewById(R.id.lc_table);
        mRvIndex = findViewById(R.id.rv_index);

        initData();
    }

    private void initData() {
        HttpUtils.post("get_weather", new HttpUtils().setParam("UserName", "admin"), response -> {
            WeatherBean weatherBean = new Gson().fromJson(response.toString(), WeatherBean.class);
            SimpleDateFormat date = new SimpleDateFormat("yyyy年MM月dd日 EEEE", Locale.CHINA);
            mTvTitle.setText(String.format(Locale.CHINA, "江西\t%s\t\t\t%d度\t 晴", date.format(new Date()), weatherBean.getWCurrent()));
            mIvStateImage.setImageDrawable(getDrawable(R.mipmap.weather));
            showView(weatherBean);
        });
    }

    private void showView(WeatherBean weatherBean) {
        ArrayList<Map> maps = new ArrayList<>();
        for (WeatherBean.ROWSDETAILBean rowsdetailBean : weatherBean.getROWS_DETAIL()) {
            HashMap<String, Object> data = new HashMap<>();
            rowsdetailBean.getWData();
            String[] split = rowsdetailBean.getTemperature().split("~");
            data.put("时间", rowsdetailBean.getWData());
            data.put("最低", split[0]);
            data.put("最高", split[1]);
            maps.add(data);
        }
        //__________适配天气表________________
        mRvInfo.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
        mRvInfo.setAdapter(new rvInfo(maps));

        //，请求传感器数据
        HashMap<Object, Object> data = new HashMap<>();
        rvIndex rvIndex = new rvIndex(6, data);
        mRvIndex.setAdapter(rvIndex);
        CountDownTimer countDownTimer = new CountDownTimer(Long.MAX_VALUE, 3000) {
            @Override
            public void onTick(long millisUntilFinished) {
                HttpUtils.post("get_all_sense", new HttpUtils().setParam("UserName", MainActivity.userName), response -> {
                    mRvIndex.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
                    Map map = new Gson().fromJson(response.toString(), Map.class);
                    data.clear();
                    data.putAll(map);
                    rvIndex.notifyDataSetChanged();
                });
            }

            @Override
            public void onFinish() {

            }
        };
        countDownTimer.start();

        ArrayList<Entry> entriesMax = new ArrayList<>();
        ArrayList<Entry> entriesMin = new ArrayList<>();
        for (int i = 0; i < maps.size(); i++) {
            entriesMax.add(new Entry(i, Float.valueOf(maps.get(i).get("最高").toString())));
            entriesMin.add(new Entry(i, Float.valueOf(maps.get(i).get("最低").toString())));
        }
        LineDataSet lineDataMaxSet = new LineDataSet(entriesMax, "最高温度");
        lineDataMaxSet.setColor(0xffffd400);
        lineDataMaxSet.setCircleColor(0xffffd400);
        lineDataMaxSet.setValueTextColor(0xffffd400);
        lineDataMaxSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);


        LineDataSet lineDataMinSet = new LineDataSet(entriesMin, "最低温度");
        lineDataMinSet.setColor(0xff145b7d);
        lineDataMinSet.setCircleColor(0xff145b7d);
        lineDataMinSet.setValueTextColor(0xff145b7d);
        lineDataMinSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);

        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(lineDataMaxSet);
        dataSets.add(lineDataMinSet);
        LineData lineData = new LineData(dataSets);
        mLcTable.getXAxis().setEnabled(false);
        mLcTable.getAxisRight().setEnabled(false);
        mLcTable.getAxisLeft().setEnabled(false);
        Description description = new Description();
        description.setEnabled(false);
        mLcTable.setDescription(description);
        mLcTable.setData(lineData);
        mLcTable.invalidate();
    }


}

class rvInfo extends RecyclerView.Adapter<rvInfo.InitView> {
    ArrayList<Map> maps;
    private View view;


    public rvInfo(ArrayList<Map> maps) {
        this.maps = maps;
    }

    @NonNull
    @Override
    public InitView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_weather_info, parent, false);
        return new InitView(view);
    }

    @Override
    public void onBindViewHolder(@NonNull InitView holder, int position) {
        holder.mTvDay.setText(maps.get(position).get("时间").toString().replace("2020-", ""));
        String eeee = new SimpleDateFormat("EEEE", Locale.CHINA).format(new Date());
        holder.mTvWeek.setText(eeee);
        if (position == 0) {
            holder.mTvWeek.setText(eeee + "(今天)");
        }
        randomW(position, holder.mTvWeather, holder.mIvState);
    }

    private void randomW(int x, View... views) {
        TextView textView = (TextView) views[0];
        ImageView imageView = (ImageView) views[1];
        switch (x % 2) {
            case 0:
                textView.setText("晴");
                imageView.setImageDrawable(view.getContext().getDrawable(R.mipmap.w001));
                imageView.setColorFilter(R.color.Black);
                break;
            case 1:
                textView.setText("多云");
                imageView.setImageDrawable(view.getContext().getDrawable(R.mipmap.w002));
                imageView.setColorFilter(R.color.Black);
                break;
            case 2:
                textView.setText("下雨");
                imageView.setImageDrawable(view.getContext().getDrawable(R.mipmap.w003));
                imageView.setColorFilter(R.color.Black);
                break;
        }
    }

    @Override
    public int getItemCount() {
        return maps.size();
    }


    public class InitView extends RecyclerView.ViewHolder {
        TextView mTvDay;
        TextView mTvWeek;
        TextView mTvWeather;
        ImageView mIvState;

        public InitView(View itemView) {
            super(itemView);
            mTvDay = itemView.findViewById(R.id.tv_day);
            mTvWeek = itemView.findViewById(R.id.tv_week);
            mTvWeather = itemView.findViewById(R.id.tv_weather);
            mIvState = itemView.findViewById(R.id.iv_state);
        }
    }
}

class rvIndex extends RecyclerView.Adapter<rvIndex.InitView> {

    int count;
    Map response;
    private View view;


    public rvIndex(int i, HashMap<Object, Object> response) {
        this.count = i;
        this.response = response;
    }

    @NonNull
    @Override
    public InitView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_weather_info2, parent, false);
        return new InitView(view);
    }

    @Override
    public void onBindViewHolder(@NonNull InitView holder, int position) {
        switch (position) {
            case 0:
                holder.mTvTitle.setText("紫外线指数");
                holder.mIvState.setImageDrawable(view.getContext().getDrawable(R.mipmap.icon101));
                String lightIntensity = response.get("LightIntensity").toString();
                holder.mTvStateInfo.setText(lightIntensity);
                if (Float.valueOf(lightIntensity) < 1000) {
                    holder.mTvTips.setBackgroundColor(0xff4472c4);
                    holder.mTvTips.setText("弱");
                }
                if (Float.valueOf(lightIntensity) > 1000 && Float.valueOf(lightIntensity) < 3000) {
                    holder.mTvTips.setBackgroundColor(0xff00b050);
                    holder.mTvTips.setText("中等");
                }
                if (Float.valueOf(lightIntensity) > 3000) {
                    holder.mTvTips.setBackgroundColor(0xffff0000);
                    holder.mTvTips.setText("强");
                }
                break;
            case 1:
                holder.mTvTitle.setText("空气污染指数");
                holder.mIvState.setImageDrawable(view.getContext().getDrawable(R.mipmap.icon105));
                String pm25 = response.get("pm2.5").toString();
                holder.mTvStateInfo.setText(pm25);
                if (Float.valueOf(pm25) < 35) {
                    holder.mTvTips.setBackgroundColor(0xff44dc68);
                    holder.mTvTips.setText("优");
                }
                if (Float.valueOf(pm25) > 35 && Float.valueOf(pm25) < 75) {
                    holder.mTvTips.setBackgroundColor(0xff92d050);
                    holder.mTvTips.setText("良");
                }
                if (Float.valueOf(pm25) > 75 && Float.valueOf(pm25) < 115) {
                    holder.mTvTips.setBackgroundColor(0xffffff40);
                    holder.mTvTips.setText("轻度污染");
                }
                if (Float.valueOf(pm25) > 115 && Float.valueOf(pm25) < 150) {
                    holder.mTvTips.setBackgroundColor(0xffbf9000);
                    holder.mTvTips.setText("中度污染");
                }
                if (Float.valueOf(pm25) > 150) {
                    holder.mTvTips.setBackgroundColor(0xff993300);
                    holder.mTvTips.setText("重度污染");
                }
                break;
            case 2:
                holder.mTvTitle.setText("运动指数");
                holder.mIvState.setImageDrawable(view.getContext().getDrawable(R.mipmap.icon104));
                String co2 = response.get("co2").toString();
                holder.mTvStateInfo.setText(co2);
                if (Float.valueOf(co2) < 3000) {
                    holder.mTvTips.setBackgroundColor(0xff44dc68);
                    holder.mTvTips.setText("适宜");
                }
                if (Float.valueOf(co2) > 3000 && Float.valueOf(co2) < 6000) {
                    holder.mTvTips.setBackgroundColor(0xffffc000);
                    holder.mTvTips.setText("中等");
                }
                if (Float.valueOf(co2) > 6000) {
                    holder.mTvTips.setBackgroundColor(0xff8149ac);
                    holder.mTvTips.setText("不宜");
                }
                break;
            case 3:
                holder.mTvTitle.setText("穿衣指数");
                holder.mIvState.setImageDrawable(view.getContext().getDrawable(R.mipmap.icon103));
                String temperature = response.get("temperature").toString();
                holder.mTvStateInfo.setText(temperature);
                if (Float.valueOf(temperature) < 12) {
                    holder.mTvTips.setBackgroundColor(0xff3462f4);
                    holder.mTvTips.setText("寒冷");
                }
                if (Float.valueOf(temperature) > 12 && Float.valueOf(temperature) < 21) {
                    holder.mTvTips.setBackgroundColor(0xff92d050);
                    holder.mTvTips.setText("舒适");
                }
                if (Float.valueOf(temperature) > 21 && Float.valueOf(temperature) < 35) {
                    holder.mTvTips.setBackgroundColor(0xff44dc68);
                    holder.mTvTips.setText("温暖");
                }
                if (Float.valueOf(temperature) > 35) {
                    holder.mTvTips.setBackgroundColor(0xffff0000);
                    holder.mTvTips.setText("热");
                }
                break;
            case 4:
                holder.mTvTitle.setText("感冒指数");
                holder.mIvState.setImageDrawable(view.getContext().getDrawable(R.mipmap.icon102));
                String humidity = response.get("humidity").toString();
                holder.mTvStateInfo.setText(humidity);

                if (Float.valueOf(humidity) < 50) {
                    holder.mTvTips.setBackgroundColor(0xffff0000);
                    holder.mTvTips.setText("易发");
                }
                if (Float.valueOf(humidity) > 50) {
                    holder.mTvTips.setBackgroundColor(0xffffff40);
                    holder.mTvTips.setText("少发");
                }
                break;
            case 5:
                holder.mTvTitle.setText("洗车指数");
                holder.mIvState.setImageDrawable(view.getContext().getDrawable(R.mipmap.car));
                String humidity_1 = response.get("humidity").toString();
                holder.mTvStateInfo.setText(humidity_1);
                Random random = new Random();
                switch (random.nextInt() % 2) {
                    case 0:
                        holder.mTvTips.setText("不适宜");

                        break;
                    case 1:
                        holder.mTvTips.setText("不太适宜");
                        break;
                    case 2:
                        holder.mTvTips.setText("适宜");

                        break;
                }
                break;
        }
    }

    @Override
    public int getItemCount() {
        return count;
    }


    public class InitView extends RecyclerView.ViewHolder {
        TextView mTvTitle;
        ImageView mIvState;
        TextView mTvStateInfo;
        TextView mTvTips;

        public InitView(View itemView) {
            super(itemView);
            mTvTitle = itemView.findViewById(R.id.tv_title);
            mIvState = itemView.findViewById(R.id.iv_state);
            mTvStateInfo = itemView.findViewById(R.id.tv_state_info);
            mTvTips = itemView.findViewById(R.id.tv_tips);
        }
    }

}

